package com.itheima.controller;

import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 部门管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {
    @Autowired
    private DeptService deptService;
    /**
     * 查询部门列表
     */
    @GetMapping
    public Result list(/*HttpSession session*/) {
//        Object loginUser = session.getAttribute("loginUser");
//        if (loginUser == null) {
//            return Result.error("请先登录");
//        }
        log.info("list depts");
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);
    }
    /**
     * 根据id删除部门 - delete http://localhost:8080/depts?id=1
     */
    @DeleteMapping
    public Result delete(@RequestParam(value = "id",defaultValue = "2") Integer id){
        System.out.println("根据id删除部门, id=" + id);
        deptService.removeById(id);
        return Result.success();
    }
    @PostMapping
    public Result save(@RequestBody Dept dept){
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        System.out.println("新增部门, dept=" + dept);
        deptService.save(dept);

        return Result.success();
    }
    /**
     * 根据ID查询 - GET http://localhost:8080/depts/1
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        System.out.println("根据ID查询, id=" + id);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }
    @PutMapping
    public Result update(@RequestBody Dept dept){
        System.out.println("修改部门, dept=" + dept);
        deptService.updateById(dept);
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        return Result.success();
    }
}